package com.sservice.service.common;
import com.sservice.urp.entity.User;
import com.sservice.service.service.IAuthService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * Created by suweiming on 2017/12/20.
 */

public class CustomRealm extends AuthorizingRealm implements InitializingBean {

    @Autowired
    private IAuthService authService;

    /*
     *  对当前的用户进行授权的
     * 用来为当前登陆成功的用户授予权限和角色（已经登陆成功了）
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal(); // 获取用户名
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(authService.getRoles(username));
        Set<String> permissions = authService.getPermissions(username);
//        System.out.println(permissions.toArray());
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }

    /*
     * 用来验证当前登录的用户，获取认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String username = (String) token.getPrincipal();   //获取用户名

        User user = authService.getByUsername(username);
        if (user != null) {
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(
                    user.getUserName(), user.getPassword(), "CustomRealm");
            return authcInfo;
        } else {
            return null;
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }
}
